package com.lagou.client;

import com.lagou.RpcDecoder;
import com.lagou.RpcEncoder;
import com.lagou.handler.ConsumerHandler;
import com.lagou.request.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Component
public class RpcConsumerV2{

    //1.创建一个线程池对象  -- 它要处理我们自定义事件
    private static ExecutorService executorService =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //2.声明一个自定义事件处理器  UserClientHandler
    private static ConsumerHandler consumerHandler;

    private static Set<String> clazzMethodNameSet = new HashSet<>();
    //一个缓存请求的对象
    //private Map<String,>
    //3.spring启动时，进行初始化，链接服务器
    @PostConstruct
    public void initClient() throws InterruptedException {
        //1) 初始化UserClientHandler
        consumerHandler = new ConsumerHandler();
        //2)创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        //3)创建客户端的引导对象
        Bootstrap bootstrap =  new Bootstrap();
        //4)配置启动引导对象
        bootstrap.group(group)
                //设置通道为NIO
                .channel(NioSocketChannel.class)
                //设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY,true)
                //监听channel 并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取ChannelPipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //设置编码
                        pipeline.addLast(new RpcEncoder());
                        pipeline.addLast(new RpcDecoder());
                        //添加自定义事件处理器
                        pipeline.addLast(consumerHandler);
                    }
                });

        //5)连接服务端
        bootstrap.connect("127.0.0.1",8999).sync();
    }

    //4.编写一个方法,使用JDK的动态代理创建对象
    // serviceClass 接口类型,根据哪个接口生成子类代理对象;   providerParam :  "UserService#sayHello#"
    public static Object createProxy(Class<?> serviceClass) throws Exception{
        //将接口中的方法，放入set中，在动态代理对象调用中，判断执行的方法是不是接口方法，不是接口的方法不拦截。
        for (Method method : serviceClass.getMethods()) {
            clazzMethodNameSet.add(serviceClass.getName() + "#" + method.getName());
        }
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                        //非缓存方法不进行拦截
                        if (clazzMethodNameSet.contains(serviceClass.getName() + "#" + method.getName())) {
                            //构建RpcRequest对象
                            consumerHandler.setRequest(RpcRequest.build(serviceClass,method,objects));

                            //3).使用线程池,开启一个线程处理处理call() 写操作,并返回结果
                            Object result = executorService.submit(consumerHandler).get();

                            //4)return 结果
                            return result;
                        }
                        return method.invoke(o,objects);
                    }
                });
    }

}

